{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import cv2\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载图像     确保data和test是两个独立文件，data包含apple，peach和lable文件  lable包含两个花的标签文件\n",
    "def load_images_from_folder(folder):\n",
    "    images = []\n",
    "    labels = []\n",
    "    for label in os.listdir(folder):\n",
    "        label_folder = os.path.join(folder, label)\n",
    "        for filename in os.listdir(label_folder):\n",
    "            img = cv2.imread(os.path.join(label_folder, filename))\n",
    "            if img is not None:\n",
    "                images.append(img)\n",
    "                labels.append(label)\n",
    "    return images, labels\n",
    "\n",
    "data_folder = 'data'\n",
    "images, labels = load_images_from_folder(data_folder)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_features(images):\n",
    "    features = []\n",
    "    for img in images:\n",
    "# 转换为HSV颜色空间\n",
    "        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "# 计算颜色直方图\n",
    "        hist = cv2.calcHist([hsv], [0, 1, 2], None, [8, 8, 8], [0, 180, 0, 256, 0, 256])\n",
    "# 归一化\n",
    "        hist = cv2.normalize(hist, hist).flatten()\n",
    "        features.append(hist)\n",
    "    return features\n",
    "\n",
    "features = extract_features(images)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 1.0\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "# 将数据分为训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)\n",
    "\n",
    "# 使用SVM训练模型\n",
    "model = SVC(kernel='linear', probability=True,C=0.1)\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "# 测试模型\n",
    "y_pred = model.predict(X_test)\n",
    "print(\"Accuracy:\", accuracy_score(y_test, y_pred))\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# # 定义参数网格\n",
    "# param_grid = {\n",
    "# 'C': [0.1, 1, 10, 100], # 正则化参数C的候选值\n",
    "# 'kernel': ['linear', 'rbf'] # 核函数的候选值\n",
    "# }\n",
    "\n",
    "# # 创建Grid Search对象\n",
    "# grid_search = GridSearchCV(estimator=SVC(probability=True),\n",
    "# param_grid=param_grid,\n",
    "# cv=5, # 5折交叉验证\n",
    "# verbose=2, # 显示详细信息\n",
    "# n_jobs=-1) # 使用所有可用的CPU核心\n",
    "\n",
    "# # 执行Grid Search\n",
    "# grid_search.fit(X_train, y_train)\n",
    "\n",
    "# # 输出最佳参数\n",
    "# print(\"Best parameters found: \", grid_search.best_params_)\n",
    "\n",
    "# # 获取最佳模型\n",
    "# best_model = grid_search.best_estimator_\n",
    "\n",
    "# # 在测试集上评估最佳模型\n",
    "# y_pred = best_model.predict(X_test)\n",
    "# print(\"Accuracy:\", accuracy_score(y_test, y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test 1: Peach\n",
      "test 2: Apple\n",
      "test 3: Peach\n"
     ]
    }
   ],
   "source": [
    "# 加载测试图像\n",
    "test_folder = 'test'\n",
    "test_images = [cv2.imread(os.path.join(test_folder, f)) for f in os.listdir(test_folder) if f.endswith('.bmp')]\n",
    "\n",
    "# 提取特征并进行预测\n",
    "test_features = extract_features(test_images)\n",
    "test_predictions = model.predict(test_features)\n",
    "\n",
    "# 输出结果\n",
    "for i, prediction in enumerate(test_predictions):\n",
    "    print(f\"test {i + 1}: {prediction}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
